﻿#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;
/// <summary>
/// BuildSpriteAtlas
/// </summary>
public partial class ESF_Logic
{
    /// <summary>
    ///生成精灵图集
    /// </summary>
    /// <returns>精灵图集文件夹</returns>
    public static Dictionary<string, ESF_BuildSpriteAtlasFolder> BuildSpriteAtlas()
    {
        Dictionary<string,ESF_BuildSpriteAtlasFolder> folders = new Dictionary<string, ESF_BuildSpriteAtlasFolder>();
        if (spriteAtlasSettingFolder.xml.spriteAtlasRoots != null)
        {
            for (int i = 0; i < spriteAtlasSettingFolder.xml.spriteAtlasRoots.Length; i++)
            {
                //读取目录
                string spriteAtlasRoot = spriteAtlasSettingFolder.xml.spriteAtlasRoots[i];
                //保存目录
                string spriteAtlasTarget = spriteAtlasSettingFolder.xml.spriteAtlasTargets[i];

                string[] dirs = Directory.GetDirectories(spriteAtlasRoot, "*", SearchOption.AllDirectories);
                if (dirs != null && dirs.Length > 0)
                {
                    foreach (var d in dirs)
                    {
                        var cds = Directory.GetDirectories(d);
                        if (cds == null || cds.Length <= 0)
                        {//只有没有子目录的文件夹才能以此文件夹为名写入SpriteAtlas 
                            ESF_BuildSpriteAtlasFolder f = new ESF_BuildSpriteAtlasFolder(spriteAtlasRoot, spriteAtlasTarget,d);
                            if (!folders.ContainsKey(f.saveSpriteAtlasPath))
                            {
                                folders.Add(f.saveSpriteAtlasPath, f);
                            }
                        }
                    }
                }
            }
        }

        List<ESF_CollectAsset> existSpriteAtlases = CollectSpriteAtlas<ESF_CollectAsset>(spriteAtlasSettingFolder.xml.spriteAtlasTargets);
        List<string> delSpriteAtlas = new List<string>();
        Dictionary<enESF_AllLanguageClassify, Dictionary<string, Dictionary<string,ESF_BuildSpriteAtlasFolder>>> dicMap = new Dictionary<enESF_AllLanguageClassify, Dictionary<string, Dictionary<string, ESF_BuildSpriteAtlasFolder>>>();
        foreach (var key in existSpriteAtlases)
        {
            if (!folders.ContainsKey(key.path))
            {
                delSpriteAtlas.Add(key.path);
            }
        }

        foreach (var p in delSpriteAtlas)
        {
            File.Delete(p);
        }
        float progress = 0;
        List<string> enSpriteAtlas = new List<string>();
        Dictionary<string, Dictionary<string, ESF_BuildSpriteAtlasFolder>> tmpSpriteAtlas = null;
        Dictionary<string, ESF_BuildSpriteAtlasFolder> tmpfolder = null;
        List<SpriteAtlas> packs = new List<SpriteAtlas>();
        
        foreach (var key in folders)
        {
            packs.Add(key.Value.CheckSpriteAtlas());
            progress++;
            if (!enSpriteAtlas.Contains(key.Value.enESF_SpriteAtlasName))
            {
                enSpriteAtlas.Add(key.Value.enESF_SpriteAtlasName);
            }

            if (!dicMap.TryGetValue(key.Value.language, out tmpSpriteAtlas))
            {
                tmpSpriteAtlas = new Dictionary<string, Dictionary<string, ESF_BuildSpriteAtlasFolder>>();
                dicMap.Add(key.Value.language, tmpSpriteAtlas);
            }
            if (!tmpSpriteAtlas.TryGetValue(key.Value.enESF_SpriteAtlasName, out tmpfolder))
            {
                tmpfolder = new Dictionary<string, ESF_BuildSpriteAtlasFolder>();
                tmpSpriteAtlas.Add(key.Value.enESF_SpriteAtlasName, tmpfolder);
            }
            tmpfolder.Add(key.Value.enESF_LanguageRootFolderName,key.Value);

            EditorUtility.DisplayProgressBar("Set SpriteAtlas", $"【{progress}/{folders.Count}】 {key.Value.saveSpriteAtlasPath}", progress / folders.Count);
        }

        SpriteAtlasUtility.PackAllAtlases(EditorUserBuildSettings.activeBuildTarget);

        Func<enESF_AllLanguageClassify, List<string>> funLan = (lan) => {
            return dicMap[lan].Keys.ToList();
        };
        Func<enESF_AllLanguageClassify,string, Dictionary<string, ESF_BuildSpriteAtlasFolder>> funFolder = (lan,sp) => {
            return dicMap[lan][sp];
        };

        string enName = spriteAtlasSettingFolder.xml.enESF_SpriteAtlasName;
        ESF_BuildTextAsset bta = new ESF_BuildTextAsset(enName, spriteAtlasSettingFolder.xml.buildEnumSpriteAtlasFolder, enESF_UnityFileExt.CS, "");
        string code = File.ReadAllText(ESF_enResxTempleteFile.Compiler_SpriteAtlaEnumsScript_txt);
        code = code.CompilerCSharp(new
        {
            enName,
            enSpriteAtlas,
            funLan,
            funFolder,
            lans = dicMap.Keys.ToList(),
        });
        bta.SetText(code);
        bta.CreateAsset();
        AssetDatabase.SaveAssets();
        EditorUtility.ClearProgressBar();
        ESF_P.ESF_Log("BuildSpriteAtlas Succeed!");
        ESF_Utility.ExecuteMenuAssetsRefresh();        
        return folders;
    }
}
#endif
